<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <title>ExcelispatrixV0.0007</title>
        <script src="jquery.min.js"></script>
    </head>
    <style>
        td {
            border-width: 1px;
            border-style: dotted;
        }
    </style>
    <body>
        <table class="BIGTABLE">
        </table>

<script>
SAVE = function(){
    localStorage.setItem('tabledata', JSON.stringify(DATA))
}

if(0){
$.fn.extend({
    myeval : function() {
        let code = this.code
        if (code[0]==='=') {
            return Function(code.substr(1)).call(this)
        }
        return code
    }
})
}

function createLATTICE (i, j)
{
    var $o = $(`<td id="${i}_${j}"></td>`)
    $o.i = i
    $o.j = j

    Object.defineProperties($o,  {
        code:{
            get: function(){
                return DATA[this.i][this.j]
            },

            set: function(s){
                DATA[this.i][this.j] = s
                SAVE()
            }
        }
    })

    if(1){
    $o.myeval = function() {
        let code = this.code
        if (code[0]==='=') {
            return Function(code.substr(1)).call(this)
        }
        return code
    }
    }
    $o.dblclick(function(){
        var $thisTD = $o

        var OLDVALUE = $thisTD.text()

        //创建一个输入区
        let $textarea = $thisTD.html('<textarea></textarea>').children().first()

        $textarea.text($thisTD.code)

        $textarea.keydown(function(e){
            //ctrl+enter
            if(e.ctrlKey && e.key === 'Enter') {
                let code = $textarea.val()
                $thisTD.code = code

                var value = $thisTD.myeval()
                $thisTD.text(value)
                console.log(value)
            }
            //ESC
            if('Escape' === e.key) {
                $thisTD.code =  $textarea.val()
                $thisTD.text(OLDVALUE)
            }

        });

        $textarea.focus()
    })


    return $o
}


if (!localStorage.getItem('tabledata')){
    localStorage.setItem('tabledata', 
        JSON.stringify([['双击此处']]))
}

DATA = JSON.parse(localStorage.getItem('tabledata'))


LOAD = function () {
    $.AA=[]
    $.each(DATA,(i,row)=>{

        $(`<tr id="${i}"></tr>`).appendTo('.BIGTABLE')
        $.AA[i] = []
        $.each(row,(j,col)=>{
            let $td = createLATTICE(i, j)

            $td.appendTo($('.BIGTABLE').last())
            $td.text($td.myeval())
        })
    })
};LOAD()

$('body').keydown(e=>{
    console.log(e)
})

</script>
</body>
</html>
